

package com.hazelcast.internal.ascii.memcache;

import com.hazelcast.internal.ascii.TextCommandService;
import com.hazelcast.logging.ILogger;

import static com.hazelcast.internal.util.StringUtil.stringToBytes;

/**
 * Produced {@link MemcacheEntry} from key and values
 */
public final class EntryConverter {
    private final TextCommandService textCommandService;
    private final ILogger logger;

    public EntryConverter(TextCommandService textCommandService, ILogger logger) {
        this.textCommandService = textCommandService;
        this.logger = logger;
    }

    public MemcacheEntry toEntry(String key, Object value) {
        if (value == null) {
            return null;
        }

        MemcacheEntry entry = null;
        if (value instanceof MemcacheEntry memcacheEntry) {
            entry = memcacheEntry;
        } else
            if (value instanceof byte[] bytes) {
                entry = new MemcacheEntry(key, bytes, 0);
            } else
                if (value instanceof String string) {
                    entry = new MemcacheEntry(key, stringToBytes(string), 0);
                } else {
                    try {
                        entry = new MemcacheEntry(key, textCommandService.toByteArray(value), 0);
                    } catch (Exception e) {
                        logger.warning(e);
                    }
                }
        return entry;
    }
}
